import { Router, Request, Response } from 'express';
import { ProfileModel } from '../models/profile.model';
import { authenticateToken } from '../middlewares/auth.middleware';
import { upload } from '../middlewares/upload.middleware';

const router = Router();

// 创建用户资料(带文件上传)
router.post('/setProfile', authenticateToken, upload.single('photo'), async (req: Request, res: Response) => {
  try {
    const profileData = {
      ...req.body,
      photo: req.file ? `/imgs/${req.file.filename}` : null
    };
    if(!profileData.userId){
      res.status(400).json({code: 0, message: '缺少userId参数'});
      return;
    }
    
    const profile = await ProfileModel.update(profileData.userId, profileData);
    res.json({code: 1, message: '修改成功', data: profile});
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({code: 0, message});
  }
});

// 获取用户资料
router.get('/:userId', async (req: Request, res: Response) => {
  try {
    const profile = await ProfileModel.findByUserId(Number(req.params.userId));
    if (profile) {
      res.json({code: 1, message: '获取成功', data: profile});
    } else {
      res.status(404).json({code: 0, message: '资料不存在'});
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({code: 0, message});
  }
});

// 更新用户资料
router.put('/:userId', async (req: Request, res: Response) => {
  try {
    const success = await ProfileModel.update(
      Number(req.params.userId), 
      req.body
    );
    if (success) {
      res.json({code: 1, message: '更新成功'});
    } else {
      res.status(404).json({code: 0, message: '用户不存在'});
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({code: 0, message});
  }
});

export default router;
